package com.gs.common.util

import android.graphics.Bitmap
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.gs.common.callback.HttpCallback
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.FormBody
import okhttp3.HttpUrl
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.net.CookieManager
import java.net.CookiePolicy
import java.util.concurrent.TimeUnit
import kotlin.random.Random

object OkHttpUtils {

    private val okHttpClient: OkHttpClient
    private val handler = Handler(Looper.getMainLooper())
    private val mCookieStore = HashMap<String, List<Cookie>>()
    val cookieJar: CookieJar

    /*同步get请求 call.execute()*/
//    fun doGet(url: String): String {
//        val request = Request.Builder().url(url).build()
//        val call = okHttpClient.newCall(request)
//        val response = call.execute()
//        return response.body?.string() ?: "null"
//    }

    /*异步get请求 call.execute()*/
    fun doGet(url: String, callback: HttpCallback) {
        val request = Request.Builder().get().url(url).build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback{
            override fun onFailure(call: Call, e: IOException) {
                    callback.onError(call, e)
            }
            override fun onResponse(call: Call, response: Response) {
                    callback.onSuccess(call, response.body?.string() ?: "null", response)
                    Log.d("response", "${mCookieStore.size}")
            }
        })
    }

    fun doPost(url: String, callback: HttpCallback, vararg keyValues: Pair<String, String?>) {
        val hashMap = HashMap<String, String?>()
        for (item in keyValues) {
            hashMap[item.first] = item.second
        }
        val formBody = FormBody.Builder()
        for (param in hashMap.keys) {
            formBody.add(param, hashMap[param] ?: "")
        }
        val request = Request.Builder().post(formBody.build()).url(url).build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback{
            override fun onFailure(call: Call, e: IOException) {
                callback.onError(call,e)
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d("response", "${mCookieStore.size}")
                callback.onSuccess(call, response.body?.string() ?: "null", response)
            }
        })
    }

    fun doPostWithPicture(url: String, picture: Bitmap, callback: HttpCallback) {
        // 创建MultipartBody.Builder用于构建请求体
        val requestBodyBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)
        // 将Bitmap对象转换为字节数组
        val byteArrayOutputStream = ByteArrayOutputStream()
        picture.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
        val imageBytes = byteArrayOutputStream.toByteArray()
        // 添加图片字节数组到请求体中
        requestBodyBuilder.addFormDataPart("file", "p${Random.nextInt(0,100000)}.jpg", RequestBody.create("image/jpeg".toMediaTypeOrNull(), imageBytes))
        // 构建请求体
        val requestBody = requestBodyBuilder.build()
        val request = Request.Builder().url(url).post(requestBody).build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback{
            override fun onFailure(call: Call, e: IOException) {
                callback.onError(call,e)
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d("response", "${mCookieStore.size}")
                callback.onSuccess(call, response.body?.string() ?: "null", response)
            }
        })
    }

    init {
        val cookieManager = CookieManager()
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
        cookieJar = object : CookieJar {
            override fun loadForRequest(url: HttpUrl): List<Cookie> {
                val list = mCookieStore.get(url.host)
                return list ?: ArrayList<Cookie>()
            }

            override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
                mCookieStore.put(url.host, cookies)
            }
        }

        val httpLoggingInterceptor = HttpLoggingInterceptor() // 日志拦截器
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        okHttpClient = OkHttpClient.Builder()
            .connectTimeout(3, TimeUnit.SECONDS)
            .cookieJar(cookieJar)
            .addInterceptor(httpLoggingInterceptor)
            .build()
    }
}